<?php
// +----------------------------------------------------------------------
// | HisiPHP框架[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2021 http://www.HisiPHP.com
// +----------------------------------------------------------------------
// | HisiPHP承诺基础框架永久免费开源，您可用于学习和商用，但必须保留软件版权信息。
// +----------------------------------------------------------------------
// | Author: 橘子俊 <364666827@qq.com>，开发者QQ群：50304283
// +----------------------------------------------------------------------

namespace app\common\service;

use app\common\service\Base;
use think\facade\Cache;

class Depart extends Base
{

	/**
	 * 获取键值对缓存
	 *
	 * @author KING
	 * @date 2020年6月9日
	 *
	 * @param int $factoryId
	 *
	 * @return array
	 */
	public function getKVCache($factoryId=null) {
		$key = KV_DEPART . ($factoryId!==null?"_" . $factoryId:'');
		$data = cache($key);
		if(!$data) {
			$this->updateKVCache();
		} else return $data;
		$data = cache($key);
		return $data?:[];
	}

	/**
	 * 更新键值对缓存
	 *
	 * @author KING
	 * @date 2020年6月9日
	 *
	 */
	public function updateKVCache() {
		$where['status'] = 1;
		$order = "factory_id asc, id desc";
		$list = db('depart')->where($where)->order($order)->column('id,factory_id,name');
		$result = [];
		$resultAll = [];
		foreach ($list as $v) {
			$result[$v['factory_id']][$v['id']] = $v['name'];
			$resultAll[$v['id']] = $v['name'];
		}
		$resultCommon = arrayGet($result, 0, []);
		foreach ($result as $factoryId => $v) {
			cache(KV_DEPART."_".$factoryId, $resultCommon+$v);
		}
		cache(KV_DEPART, $resultAll);
		return true;
	}

}